/* 
这个仓库是用户登录和注册的仓库
*/

import {reqGetCode, reqUserRegister, reqUserLogin, reqUserInfo, reqLogOut} from '../../api'


const state = {
  code: '',
  // 直接从本地存储中拿token
  token: localStorage.getItem('TOKEN'),
  userInfo: {},
};

const mutations = {
  SAVECODE(state, code){
    state.code = code
  },
  SAVETOKEN(state, token){
    state.token = token
  },
  GETUSERINFO(state, userInfo){
    state.userInfo = userInfo
  },
  CLEARUSERINFO(state){
    // 清除本地存储的信息
    localStorage.removeItem('TOKEN')
    // 清除用户仓库的信息 
    state.token = ''
    state.userInfo = {}
  }
};

const actions = {
  // 获取验证码
  async getCode({commit}, phone){
    // 获取验证码这个接口，把验证码返回，但正常的情况下后台是把验证码发送到用户手机上的。
    let result = await reqGetCode(phone)
    if(result.code == 200){
      commit('SAVECODE', result.data)
      return 'ok'
    }else{
      return Promise.reject(new Error('fail'))
    }
  },
  // 用户注册
  async userRegister({commit},user){
    let result = await reqUserRegister(user)
    console.log(result);
    if (result.code == 200){
      return 'ok'
    }else{
      return Promise.reject(new Error('fail'))
    }
  },
  // 用户登录
  async userLogin({commit}, data){
    let result = await reqUserLogin(data)
    // console.log(result);
    if(result.code == 200){
      commit('SAVETOKEN', result.data.token)
      // 进行持久化存储token,防止再次刷新页面token消失,这里使用的是本地存储
      localStorage.setItem('TOKEN', result.data.token)
      return 'ok'
    }else{
      return Promise.reject(new Error('fail'))
    }
  },
  // 获取用户信息
  async getUserInfo({commit}){
    let result = await reqUserInfo()
    if (result.code == 200){
      commit('GETUSERINFO', result.data)
    }
  },
  // 用户退出登录
  async userLogOut({commit}){
    let result = await reqLogOut()
    if(result.code == 200){
      commit('CLEARUSERINFO')
      return 'ok'
    }else{
      return Promise.reject(new Error('fail'))
    }
  }
};

const getters = {};



export default {
  state,
  mutations,
  actions,
  getters
}